package com.jojo.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jojo.domain.Notice;
import com.jojo.model.Result;
import com.jojo.service.NoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 公告业务管理控制层
 */
@Api(tags = "公告业务接口管理")
@RequestMapping("shop/notice")
@RestController
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @ApiOperation("多条件分页查询公告列表")
    @GetMapping("page")
    @PreAuthorize("hasAuthority('shop:notice:page')")
    public Result<Page<Notice>> loadNoticePage(@RequestParam Long current,
                                               @RequestParam Long size,
                                               @RequestParam (required = false) String title,
                                               @RequestParam (required = false) Integer status,
                                               @RequestParam (required = false) Integer isTop){
        Page<Notice> page = new Page<>(current,size);
        //多条件分页查询公告列表
        page = noticeService.page(page,new LambdaQueryWrapper<Notice>()
                .like(StringUtils.hasText(title),Notice::getTitle,title)
                .eq(ObjectUtil.isNotNull(status),Notice::getStatus,status)
                .eq(ObjectUtil.isNotNull(isTop),Notice::getIsTop,isTop)
                .orderByDesc(Notice::getCreateTime)
        );
        return Result.success(page);
    }

    @ApiOperation("新增公告")
    @PostMapping
    @PreAuthorize("hasAuthority('shop:notice:save')")
    public Result<?> saveNotice(@RequestBody Notice notice){
        Boolean saved = noticeService.saveNotice(notice);
        return Result.handle(saved);
    }

    @ApiOperation("根据标识查询公告详情")
    @GetMapping("info/{noticeId}")
    @PreAuthorize("hasAuthority('shop:notice:info')")
    public Result<Notice> loadNoticeInfoById(@PathVariable Long noticeId){
        Notice notice = noticeService.getById(noticeId);
        return Result.success(notice);
    }

    @ApiOperation("修改公告内容")
    @PutMapping
    @PreAuthorize("hasAuthority('shop:notice:update')")
    public Result<?> modifyNotice(@RequestBody Notice notice){
        Boolean updated = noticeService.modifyNotice(notice);
        return Result.handle(updated);
    }

    @ApiOperation("根据公告标识删除公告")
    @DeleteMapping("{noticeId}")
    @PreAuthorize("hasAuthority('shop:notice:delete')")
    public Result<?> removeNotice(@PathVariable Long noticeId){
        Boolean removed = noticeService.removeById(noticeId);
        return Result.handle(removed);
    }

}
